# gozerbot/utils/xmldict.py
#
#

"""
    this module contains the xml dict class 
"""


## IMPORT SECTION

# gozerbot imports
from gozerbot.datadir import datadir
from gozerbot.config import Config, config
from gozerbot.utils.generic import toenc, jabberstrip
from gozerbot.utils.log import rlog
from gozerbot.utils.lazydict import LazyDict
from gozerbot.utils.exception import handle_exception
from gozerbot.utils.locking import lockdec
from gozerbot.utils.trace import whichmodule

# basic imports
import time, copy, logging

## END IMPORT

## LOCK SECTION

# locks

## END LOCK

def XMLescape(data):
    pass

class XMLDict(LazyDict):


    """
        dictionairy to store xml stanza attributes.

        :params input: optional dict to init with
        :type input: dict

    """

    def __init__(self, input={}):

        if input == None:
            LazyDict.__init__(self)
        else:
            LazyDict.__init__(self, input)

        try:
            self['fromm'] = self['from']
        except (KeyError, TypeError):
            self['fromm'] = ''

    def __getattr__(self, name):

        """
            override getattribute so nodes in payload can be accessed.

        """

        if not self.has_key(name) and self.has_key('subelements'):

            for i in self['subelements']:

                if name in i:
                    return i[name]

        return LazyDict.__getattr__(self, name, default="")

    def get(self, name):

        """
            get a attribute by name.

            :param name: name of the attribute
            :type name: string

            .. literalinclude:: ../../../gozerbot/xmpp/core.py
                :pyobject: XMLDict.get

        """

        if self.has_key('subelements'):

            for i in self['subelements']:

                if name in i:

                    return i[name]

        if self.has_key(name):

            return self[name]

        return LazyDict()

    def toxml(self):

        """
            convert the dictionary to xml.

            .. literalinclude:: ../../../gozerbot/xmpp/core.py
               :pyobject: XMLDict.toxml
        """

        res = dict(self)

        if not res:
            raise Exception("%s .. toxml() can't convert empty dict" % self.name)

        rlog(-1, self.name, u"toxml input: %s" % res)
        elem = self['element']
        main = "<%s" % self['element']

        for attribute in attributes[elem]: 

            if attribute in res:

                if res[attribute]:
                    main += u" %s='%s'" % (attribute, XMLescape(res[attribute]))

                continue

        main += ">"
        gotsub = False

        if res.has_key('txt'):

            if res['txt']:

                main += u"<body>%s</body>" % XMLescape(res['txt'])
                gotsub = True

        for subelement in subelements[elem]:

            try:
                data = res[subelement]

                if data:
                    main += "<%s>%s</%s>" % (subelement, XMLescape(data), subelement)
                    gotsub = True

            except KeyError:
                pass

        if gotsub:

            main += "</%s>" % elem

        else:

            main = main[:-1]
            main += "/>"

        return main

    def str(self):

        """
            convert to string.

            .. literalinclude:: ../../../gozerbot/xmpp/core.py
                :pyobject: XMLDict.str
        """

        result = ""
        elem = self['element']
        for item, value in dict(self).iteritems():
            if item in attributes[elem] or item in subelements[elem] or item == 'txt':
                result += "%s='%s' " % (item, value)
        return result
 

## INIT SECTION

# no vars

## END INIT
